package com.ledou44.ledousrad.servicehandler;

import com.alibaba.fastjson.JSON;
import com.ledou44.ledousrad.dto.LedouSradDTO;
import com.ledou44.ledousrad.service.DiscoveryService;
import com.ledou44.ledousrad.service.RegisterService;
import com.ledou44.ledousrad.sradenum.LedouSradEnum;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.net.InetSocketAddress;

/**
 * @author ledou44
 * 默认handler
 */
@Slf4j
public class DefaultServiceHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LedouSradDTO ledouSradDTO = null;
        try {
            ledouSradDTO = JSON.parseObject(String.valueOf(msg), LedouSradDTO.class);
        }catch (Exception e) {
            InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
            String address = socketAddress.getAddress().getHostAddress();
            Integer port = socketAddress.getPort();
            log.warn("来自"+address+":"+port+"的错误的请求，已丢弃！");
        }
        if(ledouSradDTO == null) {
            return;
        }

        if(ledouSradDTO.getType().equals(LedouSradEnum.SERVICE_REGISTER.getCode())) {
            if(!CollectionUtils.isEmpty(ledouSradDTO.getServiceList())) {
                InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
                String address = socketAddress.getAddress().getHostAddress();
                String key = String.valueOf(ctx.hashCode());
                RegisterService.registerService(ledouSradDTO.getServiceList(),key,address);
            }
        } else if(ledouSradDTO.getType().equals(LedouSradEnum.SERVICE_DISCOVERY.getCode())) {
            LedouSradDTO discoveryResult = DiscoveryService.getService(ledouSradDTO);
            ctx.writeAndFlush(JSON.toJSONString(discoveryResult));
        }
        //将消息传递给下一个handler
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String key = String.valueOf(ctx.hashCode());
        RegisterService.deleteRegisterService(key);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {}
}
